/*
 *  Copyright (C) 2005-2007 Renier Roth
 *  www.renier.de
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.renier.jkeepass;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import de.renier.jkeepass.actions.ActionManager;
import de.renier.jkeepass.actions.OpenAction;
import de.renier.jkeepass.util.LocalProperties;
import de.renier.jkeepass.util.Utils;

/**
 * JKeePass
 *
 * @author <a href="mailto:software@renier.de">Renier Roth</a>
 */
public class JKeePass extends JFrame implements ClipboardOwner {

  private static final long serialVersionUID = 1L;
  public static JKeePass application = null;
  private boolean modified = false;
  private JPanel jContentPane = null;
  private JMenuBar mainMenuBar = null;
  private JMenu fileMenu = null;
  private JMenu infoMenu = null;
  private JToolBar toolBar = null;
  private JSplitPane jSplitPane = null;
  private ElementTreePanel elementTreePanel = null;
  private ContainerElementPanel containerElementPanel = null;
  private JMenu lastOpenedMenu = null;
  private File openFile = null;  //  @jve:decl-index=0:
  private JMenu extraMenu = null;
  
  /**
   * This method initializes mainMenuBar	
   * 	
   * @return javax.swing.JMenuBar	
   */
  private JMenuBar getMainMenuBar() {
    if (mainMenuBar == null) {
      mainMenuBar = new JMenuBar();
      mainMenuBar.add(getFileMenu());
      mainMenuBar.add(getExtraMenu());
      mainMenuBar.add(getInfoMenu());
    }
    return mainMenuBar;
  }

  /**
   * This method initializes fileMenu	
   * 	
   * @return javax.swing.JMenu	
   */
  private JMenu getFileMenu() {
    if (fileMenu == null) {
      fileMenu = new JMenu();
      fileMenu.setText(Messages.getString("JKeePass.0")); //$NON-NLS-1$
      fileMenu.setMnemonic(KeyEvent.VK_F);
      fileMenu.add(ActionManager.getOpenAction());
      fileMenu.add(ActionManager.getSaveAction());
      fileMenu.add(ActionManager.getSaveAsAction());
      fileMenu.addSeparator();
      fileMenu.add(getLastOpenedMenu());
      fileMenu.add(ActionManager.getCloseAction());
    }
    return fileMenu;
  }

  /**
   * This method initializes infoMenu	
   * 	
   * @return javax.swing.JMenu	
   */
  private JMenu getInfoMenu() {
    if (infoMenu == null) {
      infoMenu = new JMenu();
      infoMenu.setText(Messages.getString("JKeePass.1")); //$NON-NLS-1$
      infoMenu.setMnemonic(KeyEvent.VK_I);
      infoMenu.add(ActionManager.getAboutAction());
    }
    return infoMenu;
  }

  /**
   * This method initializes toolBar	
   * 	
   * @return javax.swing.JToolBar	
   */
  private JToolBar getToolBar() {
    if (toolBar == null) {
      toolBar = new JToolBar();
      toolBar.add(ActionManager.getCloseAction()).setToolTipText(Messages.getString("JKeePass.2")); //$NON-NLS-1$
      toolBar.addSeparator();
      toolBar.add(ActionManager.getOpenAction()).setToolTipText(Messages.getString("JKeePass.3")); //$NON-NLS-1$
      toolBar.add(ActionManager.getSaveAction()).setToolTipText(Messages.getString("JKeePass.4")); //$NON-NLS-1$
      toolBar.add(ActionManager.getSaveAsAction()).setToolTipText(Messages.getString("JKeePass.5")); //$NON-NLS-1$
      toolBar.addSeparator();
      toolBar.add(ActionManager.getCreateContainerAction()).setToolTipText(Messages.getString("JKeePass.6")); //$NON-NLS-1$
      toolBar.add(ActionManager.getCreateBasicElementAction()).setToolTipText(Messages.getString("JKeePass.7")); //$NON-NLS-1$
      toolBar.addSeparator();
      toolBar.add(ActionManager.getDeleteContainerElementAction()).setToolTipText(Messages.getString("JKeePass.8")); //$NON-NLS-1$
      toolBar.add(ActionManager.getDeleteBasicElementAction()).setToolTipText(Messages.getString("JKeePass.9")); //$NON-NLS-1$
      toolBar.addSeparator();
      toolBar.add(ActionManager.getTogglePasswordVisibilityInTableAction()).setToolTipText(Messages.getString("JKeePass.10")); //$NON-NLS-1$
      toolBar.add(ActionManager.getAddPasswordToClibboardAction()).setToolTipText(Messages.getString("JKeePass.19")); //$NON-NLS-1$
      toolBar.addSeparator();
      toolBar.add(ActionManager.getPreferencesAction()).setToolTipText(Messages.getString("JKeePass.11")); //$NON-NLS-1$
      toolBar.add(ActionManager.getAboutAction()).setToolTipText(Messages.getString("JKeePass.12")); //$NON-NLS-1$
    }
    return toolBar;
  }

  /**
   * This method initializes jSplitPane	
   * 	
   * @return javax.swing.JSplitPane	
   */
  private JSplitPane getJSplitPane() {
    if (jSplitPane == null) {
      jSplitPane = new JSplitPane();
      jSplitPane.setDividerSize(3);
      jSplitPane.setDividerLocation(200);
      jSplitPane.setLeftComponent(getElementTreePanel());
      jSplitPane.setRightComponent(getContainerElementPanel());
    }
    return jSplitPane;
  }
  
  /**
   * This method initializes elementTreePanel	
   * 	
   * @return de.renier.jkeepass.ElementTreePanel	
   */
  public ElementTreePanel getElementTreePanel() {
    if (elementTreePanel == null) {
      elementTreePanel = new ElementTreePanel();
    }
    return elementTreePanel;
  }
  
  public ContainerElementPanel getContainerElementPanel() {
    if (containerElementPanel == null) {
      containerElementPanel = new ContainerElementPanel();
    }
    return containerElementPanel;
  }

  /**
   * This method initializes lastOpenedMenu	
   * 	
   * @return javax.swing.JMenu	
   */
  private JMenu getLastOpenedMenu() {
    if (lastOpenedMenu == null) {
      lastOpenedMenu = new JMenu();
      lastOpenedMenu.setText(Messages.getString("JKeePass.13")); //$NON-NLS-1$
      lastOpenedMenu.setIcon(new ImageIcon(getClass().getResource("/org/javalobby/icons/20x20/Copy.gif"))); //$NON-NLS-1$
      // get last opened files and put menu entries
      refreshLastOpenedFiles();
    }
    return lastOpenedMenu;
  }

  /**
   * refreshLastOpenedFiles
   */
  public void refreshLastOpenedFiles() {
    lastOpenedMenu.removeAll();
    List files = Utils.getLastOpenedFiles();
    Iterator it = files.iterator();
    while (it.hasNext()) {
      File file = (File)it.next();
      lastOpenedMenu.add(new JMenuItem(new OpenAction(file)));
    }
  }  
  
  /**
   * This method initializes extraMenu	
   * 	
   * @return javax.swing.JMenu	
   */
  private JMenu getExtraMenu() {
    if (extraMenu == null) {
      extraMenu = new JMenu();
      extraMenu.setText(Messages.getString("JKeePass.15")); //$NON-NLS-1$
      extraMenu.add(ActionManager.getPreferencesAction());
      extraMenu.add(ActionManager.getCreateTanElementAction());
      extraMenu.add(ActionManager.getSetPasswordAction());
      extraMenu.add(ActionManager.getExportPlainAction());
    }
    return extraMenu;
  }

  /**
   * main
   *
   * @param args
   */
  public static void main(String[] args) {
    // init style
    Utils.styleChange(LocalProperties.getInstance().getProperty(LocalProperties.PROP_SYSTEM_STYLE));

    // run ap
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        application = new JKeePass();
        application.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        application.setVisible(true);
        
        // do something after start
        application.afterStart();
      }
    });
  }

  
  private void afterStart() {
    // check if we have to open the last file
    String quickOpen = LocalProperties.getInstance().getProperty(LocalProperties.PROP_QUICKOPEN);
    if (Boolean.valueOf(quickOpen).booleanValue()) {
      // open last file, if exist
      List lastOpened = Utils.getLastOpenedFiles();
      if (lastOpened != null && !lastOpened.isEmpty()) {
        File lastFile = (File)lastOpened.get(0);
        if (lastFile.canRead()) {
          // open file
          new OpenAction(lastFile).actionPerformed(new ActionEvent(this,0,"open")); //$NON-NLS-1$
        }
      }
      
    }
  }
  
  /**
   * This is the default constructor
   */
  public JKeePass() {
    super();
    initialize();
  }

  /**
   * This method initializes this
   * 
   * @return void
   */
  private void initialize() {
    this.setSize(800, 600);
    this.setJMenuBar(getMainMenuBar());
    this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/org/javalobby/icons/20x20/Key.gif"))); //$NON-NLS-1$
    this.setContentPane(getJContentPane());
    this.setTitle(Messages.getString("JKeePass.18")); //$NON-NLS-1$
    // center window
    setLocationRelativeTo(null);
    // close handler
    this.addWindowListener(new java.awt.event.WindowAdapter() { 
      public void windowClosing(java.awt.event.WindowEvent e) {    
        ActionManager.getCloseAction().actionPerformed(new ActionEvent(this,0,"close")); //$NON-NLS-1$
      }
    });
    
    // set listener
    getElementTreePanel().addTreeSelectionListener(getContainerElementPanel());
  }

  /**
   * This method initializes jContentPane
   * 
   * @return javax.swing.JPanel
   */
  private JPanel getJContentPane() {
    if (jContentPane == null) {
      jContentPane = new JPanel();
      jContentPane.setLayout(new BorderLayout());
      jContentPane.add(getToolBar(), BorderLayout.NORTH);
      jContentPane.add(getJSplitPane(), BorderLayout.CENTER);
    }
    return jContentPane;
  }

  /**
   * isModified
   *
   * @return Returns the modified.
   */
  public boolean isModified() {
    return modified;
  }

  /**
   * setModified
   *
   * @param modified The modified to set.
   */
  public void setModified(boolean modified) {
    this.modified = modified;
    // if we have a file
    if (openFile != null) {
      ActionManager.getSaveAction().setEnabled(modified);
    }
  }

  /**
   * getOpenFile
   *
   * @return Returns the openFile.
   */
  public File getOpenFile() {
    return openFile;
  }

  /**
   * setOpenFile
   *
   * @param openFile The openFile to set.
   */
  public void setOpenFile(File openFile) {
    this.openFile = openFile;
  }

  /* (non-Javadoc)
   * @see java.awt.datatransfer.ClipboardOwner#lostOwnership(java.awt.datatransfer.Clipboard, java.awt.datatransfer.Transferable)
   */
  public void lostOwnership(Clipboard clipboard, Transferable transferable) {
    // do nothing
  }

}
